<script lang="ts" setup>
import { reactive, ref, toRefs, watch } from "vue";
import type { TabsPaneContext, UploadFile } from "element-plus";
import { useRoute } from "vue-router";
import {
  getCreateTimelist,
  getPriceAsclist,
  getPriceDesclist,
  getProductList,
  getProductSoldlist,
} from "@/api/product/product";
import router from "@/router";
import { useCounterStore } from "@/stores/counter";
import { addCartItme } from "@/api/cart/cartItem";
import type { Product } from "@/types/index";
import { addFavorite } from "@/api/favorite/favorite";

interface CartItem {
  productId: number | null;
  quantity: number;
  priceSnapshot: number | null;
  addedAt: string;
  isChosen: number;
}
const cartItem = ref<CartItem>({
  productId: null,
  quantity: 1,
  priceSnapshot: null,
  addedAt: "",
  isChosen: 0,
});
const isPrice = ref(false);
const total = ref(0);
const productList = ref<Product[]>([]);
const activeName = ref("synthesis");
const loading = ref(false);
const activeNameList = ref([
  { label: "综合", name: "synthesis" },
  { label: "销量", name: "xiaoliang" },
  { label: "新品", name: "xinping" },
  { label: "价格", name: "jiage" },
]);
const route = useRoute();

const data = reactive({
  queryParams: <Product>{
    pageNum: 1,
    pageSize: 20,
    status: 1,
  },
});
const { queryParams } = toRefs(data);
// 获取关键词参数
const getSearchKeyword = () => {
  const keyword = Array.isArray(route.query.keyword)
    ? route.query.keyword[0] || "" // 处理数组形式参数
    : route.query.keyword || ""; // 处理普通字符串
  return decodeURIComponent(keyword);
};
const getSearchCategory = () => {
  const category = Array.isArray(route.query.category)
    ? route.query.category[0] || "" // 处理数组形式参数
    : route.query.category || ""; // 处理普通字符串
  return decodeURIComponent(category);
};
// 搜索列表
async function getSearchList() {
  loading.value = true;
  queryParams.value.name = getSearchKeyword();
  queryParams.value.categoryName = getSearchCategory();
  await getProductList(queryParams.value).then((response) => {
    productList.value = response.data.rows;
    total.value = response.data.total;
  });
  loading.value = false;
}
//加入采花车按钮
const addCartItemButton = async (item: Product) => {
  cartItem.value.priceSnapshot = item.price;
  cartItem.value.productId = item.productId;
  await addCartItme(cartItem.value).then((response) => {
    console.log(response.data.msg);
  });
  router.push("/cart");
  console.log(item);
};
// 点击商品
const selectGoods = (item: any) => {
  // 跳转
  router.push("/product/detail/" + item.productId);
};
const handleClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.paneName === "synthesis") {
    queryParams.value.name = getSearchKeyword();
    queryParams.value.categoryName = getSearchCategory();
    getProductList(queryParams.value).then((response) => {
      productList.value = response.data.rows;
      total.value = response.data.total;
    });
  } else if (tab.paneName === "xiaoliang") {
    queryParams.value.name = getSearchKeyword();
    queryParams.value.categoryName = getSearchCategory();
    getProductSoldlist(queryParams.value).then((response) => {
      productList.value = response.data.rows;
      total.value = response.data.total;
    });
  } else if (tab.paneName === "xinping") {
    queryParams.value.name = getSearchKeyword();
    queryParams.value.categoryName = getSearchCategory();
    getCreateTimelist(queryParams.value).then((response) => {
      productList.value = response.data.rows;
      total.value = response.data.total;
    });
  } else if (tab.paneName === "jiage") {
    queryParams.value.name = getSearchKeyword();
    queryParams.value.categoryName = getSearchCategory();
    isPrice.value = !isPrice.value;
    if (isPrice.value) {
      getPriceAsclist(queryParams.value).then((response) => {
        productList.value = response.data.rows;
        total.value = response.data.total;
      });
    } else {
      getPriceDesclist(queryParams.value).then((response) => {
        productList.value = response.data.rows;
        total.value = response.data.total;
      });
    }
  }
};
// 当前页
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getSearchList();
};
//加入收藏按钮
const addFavoriteButton = async (item: Product) => {
  await addFavorite(item);
};
watch(getSearchKeyword, (newValue, oldValue) => {
  getSearchList();
});
console.log(productList.value);
getSearchList();
</script>

<template>
  <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
    <el-tab-pane
      :label="item.label"
      :name="item.name"
      v-for="item in activeNameList"
      v-loading="loading"
    >
      <template #label>
        <span>
          <span>{{ item.label }}</span>
          <span v-if="item.name == 'jiage'">
            <span v-if="isPrice" style="color: antiquewhite">↑</span>
            <span v-else>↑</span>
          </span>
          <span v-if="item.name == 'jiage'">
            <span v-if="isPrice">↓</span>
            <span v-else style="color: antiquewhite">↓ </span>
          </span>
        </span>
      </template>
      <el-space
        wrap
        style="justify-content: center; width: 100%; margin: 0 auto; max-width: 1300px"
      >
        <el-card
          shadow="hover"
          v-if="productList.length > 0"
          v-for="item in productList"
          :key="item"
          class="card-item"
          style="width: 210px; margin: 10px; display: inline-block"
        >
          <el-image
            style="width: 100%; height: 200px"
            :src="item.img"
            fit="cover"
            @click="selectGoods(item)"
          />
          <template #footer>
            <div style="margin-left: 5px">
              <el-text truncated tag="b" @click="selectGoods(item)">
                {{ item.name }}
              </el-text>
            </div>
            <div style="margin-left: 5px">
              <el-text class="mx-1" type="danger" size="large"
                >￥{{ item.price }}
                <el-text class="mx-1" type="danger" size="small">到手价</el-text>
                <el-text class="mx-1" type="danger" size="small" style="margin-left: 10px"
                  >销量{{ item.sold }}</el-text
                >
              </el-text>
            </div>
            <el-row>
              <el-col :sapn="24">
                <el-button @click="addFavoriteButton(item)" style="width: 50%"
                  ><el-icon><Star /></el-icon>关注
                </el-button>
                <el-button @click="addCartItemButton(item)" style="width: 50%"
                  ><el-icon><ShoppingCartFull /></el-icon>加入采花车</el-button
                >
              </el-col>
            </el-row>
          </template>
        </el-card>
        <el-empty v-else description="暂无商品">
          <el-button @click="router.push('/home')" type="primary">去逛逛</el-button>
        </el-empty>
      </el-space>
    </el-tab-pane>
  </el-tabs>
  <div>
    <el-pagination
      background
      :page-size="queryParams.pageSize"
      @current-change="handleCurrentChange"
      v-model:current-page="queryParams.pageNum"
      layout="->,prev,->, pager,->, next,->,total"
      :total="total"
      style="margin-top: 20px"
    />
  </div>
</template>
<style lang="less">
.el-card__footer {
  padding: 0;
  .el-button {
    border-radius: 0;
  }
  .el-button + .el-button {
    margin-left: 0;
  }
}
.card-item {
  .el-card__body {
    padding: 0;
    height: 200px;
  }
}
</style>
